package com.pengjunlee.hive.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.pengjunlee.hive.bean.VehicleResult;
import com.pengjunlee.hive.utils.JedisUtils;

import redis.clients.jedis.Jedis;


@Service
public class JedisService {
	
	private Jedis jedis;
	
	/**
	 * 根据终端号码获取车辆实时信息
	 * @param terminalCodes
	 * @return
	 * @throws Exception 
	 * @throws InterruptedException
	 */
	public List<VehicleResult> queryVehicleInfoByTerminalCode(String terminalCodes) throws Exception {
		List<VehicleResult> list = new ArrayList<VehicleResult>();
		//判断设备号是否为空
		if(StringUtils.isBlank(terminalCodes)){
			throw new Exception("请输入设备号!");
		}
		
		//解析设备号字符串
		String[] terminalCodeArray = terminalCodes.split(",");
		if(terminalCodeArray != null && terminalCodeArray.length > 0){
			//redis初始化
			jedis = JedisUtils.getResource();
			//获取redis中所有的所有的key值
			Set<String> sets = jedis.hkeys("tm30_status_ehs3");
			
			for(int index=0; index<terminalCodeArray.length; index++){
				//车辆时间戳列表
				List<Long> lastRefreshTimeList = new ArrayList<Long>();
				
				for(String str : sets){
					String tc = str.split("-")[0];
					String tcTime = str.split("-")[1];
					if(tc.equals(terminalCodeArray[index])){
						lastRefreshTimeList.add(Long.parseLong(tcTime));
					}
				}
				//时间戳列表排序
				if(lastRefreshTimeList != null && lastRefreshTimeList.size() > 0){
					Collections.sort(lastRefreshTimeList);
				}
				
				for(int i=0; i<lastRefreshTimeList.size(); i++){
					int count = i+1;
					Long finalTime = lastRefreshTimeList.get(lastRefreshTimeList.size() - count);
					String hkey = terminalCodeArray[index] + "-" + finalTime.toString();
					String value = jedis.hget("tm30_status_ehs3", hkey);
					if(StringUtils.isBlank(value) || value.equals("{}")){
						continue;
					}else{
						VehicleResult vehicle = this.parseJson2Object(terminalCodeArray[index], finalTime.toString(), value);
						if(vehicle != null){
							list.add(vehicle);
						}
						break;
					}
				}
			}
		}
		
        return list;
	}
	
	/**
	 * 将redis中的value解析为vehicle对象
	 * @param terminalCode
	 * @param lastRefreshTime
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public VehicleResult parseJson2Object(String terminalCode, String lastRefreshTime, String jsonStr) throws Exception{
		VehicleResult vehicle = new VehicleResult();
		//判断value值是否为空
		if(StringUtils.isBlank(terminalCode)){
			throw new Exception("没有终端号!");
		}
		
		if(StringUtils.isBlank(jsonStr) || jsonStr.equals("{}")){
			return null;
		}
		
		//去掉多余的u
		String jsonResult = jsonStr.replace("u", StringUtils.EMPTY);
		//拼装数据对象
		if(StringUtils.isNotBlank(jsonStr)){
			//将字符串转换为json对象
			JSONObject jsonVehicle = JSONObject.parseObject(jsonResult);
			vehicle.setTerminalCode(terminalCode);
			
			try{
				
				if(StringUtils.isNotBlank(jsonVehicle.getString("GPS002"))){
					String lgt = JSONObject.parseObject(jsonVehicle.getString("GPS002")).getString("val");
					vehicle.setLgt(Double.parseDouble(lgt));
				}else{
					return null;
					//vehicle.setLgt(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicle.getString("GPS003"))){
					String lat = JSONObject.parseObject(jsonVehicle.getString("GPS003")).getString("val");
					vehicle.setLat(Double.parseDouble(lat));
				}else{
					return null;
					//vehicle.setLat(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicle.getString("GPS006"))){
					String angle = JSONObject.parseObject(jsonVehicle.getString("GPS006")).getString("val");
					vehicle.setAngle(Double.parseDouble(angle));
				}else{
					vehicle.setAngle(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicle.getString("V019"))){
					String speed = JSONObject.parseObject(jsonVehicle.getString("V019")).getString("val");
					vehicle.setSpeed(Double.parseDouble(speed));
				}else{
					vehicle.setSpeed(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicle.getString("V015"))){
					String totalKm = JSONObject.parseObject(jsonVehicle.getString("V015")).getString("val");
					vehicle.setTotalKm(Double.parseDouble(totalKm));
				}else{
					vehicle.setTotalKm(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicle.getString("V133"))){
					String enableKm = JSONObject.parseObject(jsonVehicle.getString("V133")).getString("val");
					vehicle.setEnableKm(Double.parseDouble(enableKm));
				}else{
					vehicle.setEnableKm(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicle.getString("E010"))){
					String powerPer = JSONObject.parseObject(jsonVehicle.getString("E010")).getString("val");
					vehicle.setSoc(Integer.parseInt(powerPer));
				}else{
					vehicle.setSoc(0);
				}
				
				vehicle.setLastRefreshTime(lastRefreshTime);
			}catch(Exception ex){
				throw new Exception(ex.getMessage());
			}
		}
		return vehicle;
	}
	
	/**
	 * 根据终端号获取车辆轨迹信息
	 * @param terminalCode
	 * @return
	 * @throws Exception 
	 */
	public List<VehicleResult> queryVehicleTrackInfoByTerminalCode(String terminalCode, String startTime, String endTime) throws Exception{
		List<VehicleResult> list = new ArrayList<VehicleResult>();
		//判断设备号是否为空
		if(StringUtils.isBlank(terminalCode)){
			throw new Exception("请输入设备号!");
		}
		//判断开始时间是否为空
		if(StringUtils.isBlank(startTime)){
			throw new Exception("请输入开始时间!");
		}
		//判断结束时间是否为空
		if(StringUtils.isBlank(endTime)){
			throw new Exception("请输入结束时间!");
		}
		
		SimpleDateFormat sdfStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long startTimeLong = sdfStart.parse(startTime).getTime();
		
		SimpleDateFormat sdfEnd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long endTimeLong = sdfEnd.parse(endTime).getTime();
		
		//redis初始化
		jedis = JedisUtils.getResource();
		//获取redis中所有的所有的key值
		Set<String> sets = jedis.hkeys("tm30_status_ehs3");
		
		//车辆时间戳列表
		List<Long> lastRefreshTimeList = new ArrayList<Long>();
		
		for(String str : sets){
			String tc = str.split("-")[0];
			String tcTime = str.split("-")[1];
			if(tc.equals(terminalCode)){
				lastRefreshTimeList.add(Long.parseLong(tcTime));
			}
		}
		//根据时间过滤后的时间戳列表
		List<Long> filterTimeList = new ArrayList<Long>();
		
		if(lastRefreshTimeList != null && lastRefreshTimeList.size() >0){
			for(Long ts : lastRefreshTimeList){
				if(ts > startTimeLong && ts < endTimeLong){
					filterTimeList.add(ts);
				}
			}
		}
		
		//时间戳列表排序
		if(filterTimeList != null && filterTimeList.size() > 0){
			Collections.sort(filterTimeList);
		}
		
		if(filterTimeList != null && filterTimeList.size() > 0){
			for(Long ts : filterTimeList){
				String hkey = terminalCode + "-" + ts.toString();
				String value = jedis.hget("tm30_status_ehs3", hkey);
				VehicleResult vehicle = this.parseJson2Object(terminalCode, ts.toString(), value);
				if(vehicle != null){
					list.add(vehicle);
				}
			}
		}
		
		return list;
	}
	
}